package com.cbgolf.oa.base;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.cbgolf.oa.R;
import com.cbgolf.oa.app.AppManager;
import com.cbgolf.oa.util.DensityUtil;
import com.cbgolf.oa.util.PermissionUtils;
import com.cbgolf.oa.util.ScreenUtil;
import com.cbgolf.oa.util.StatusBarUtil;
import com.cbgolf.oa.util.TextUtil;
import com.cbgolf.oa.util.Util;
import com.cbgolf.oa.widget.autolayout.AutoLayoutActivity;
import com.cbgolf.oa.widget.autolayout.utils.AutoUtil;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import io.reactivex.functions.Consumer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author lq
 * @date 2017/8/24
 */

public abstract class BaseActivity extends AutoLayoutActivity {

  protected Activity context;
  protected BroadcastReceiver netReceiver;

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    context = getContext();
    AppManager.getNewInstance().addActivity(this);
  }

  @Override
  public void setContentView(int layoutResID) {
    super.setContentView(layoutResID);
    setStatusBar();
    AutoUtil.auto(this);
    init();
  }

  protected void init() {
    findViews();
    setViews();
    setListener();
    loadData();

  }

  protected void loadData() {

  }

  protected void findViews() {

  }

  protected void setViews() {

  }

  protected void setListener() {

  }

  protected Activity getContext() {
    return this;
  }

  protected void setStatusBar() {
    StatusBarUtil.setStatusBarTranslucent(this, false);
//        StatusBarUtil.setTransparent(this);
//        StatusBarUtil.setColor(this, getResources().getColor(R.color.transparent));
  }

  public void registerNetListener() {
    IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    netReceiver = new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
          ConnectivityManager cm = (ConnectivityManager) getSystemService(
              Context.CONNECTIVITY_SERVICE);
          NetworkInfo networkInfo = cm.getActiveNetworkInfo();
          if (null != networkInfo && networkInfo.isConnected()) {
            netChangedHasNet();
          } else {
            netChangedNoNet();

          }
        }

      }
    };
    registerReceiver(netReceiver, filter);
  }

  protected void netChangedNoNet() {

  }

  protected void netChangedHasNet() {

  }

  protected void mStartActivity(Class c) {
    mStartActivity(c, null);
  }

  protected void mStartActivity(Class c, String key, String value) {
    Map<String, String> map = new HashMap<>();
    map.put(key, value);
    mStartActivity(c, map);
  }

  protected void mStartActivity(Class c, Map<String, String> map) {
    Intent intent = new Intent(this, c);
    if (null != map && !map.isEmpty()) {
      Set<Map.Entry<String, String>> set = map.entrySet();
      for (Map.Entry<String, String> me : set) {
        intent.putExtra(me.getKey(), me.getValue());
      }
    }
    startActivity(intent);
    overridePendingTransition(R.anim.in_from_right, R.anim.out_from_left);
  }

  @Override
  public void finish() {
    super.finish();
    overridePendingTransition(R.anim.in_from_left, R.anim.out_from_right);
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();

    if (null != netReceiver) {
      unregisterReceiver(netReceiver);
      netReceiver = null;
    }
    AppManager.getNewInstance().removeActivity(this);

  }


  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键
      onKeyBack();
      return true;
    } else if (keyCode == KeyEvent.KEYCODE_MENU) {

    } else if (keyCode == KeyEvent.KEYCODE_HOME) {
      moveTaskToBack(true);
      return true;
    }
    return super.onKeyDown(keyCode, event);
  }

  protected void onKeyBack() {
    finish();
  }


  /**
   * 程序是否在前台运行
   */
  public boolean isAppOnForeground() {
    // Returns a list of application processes that are running on the
    // device

    ActivityManager activityManager = (ActivityManager) getApplicationContext()
        .getSystemService(Context.ACTIVITY_SERVICE);
    String packageName = getApplicationContext().getPackageName();

    List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
        .getRunningAppProcesses();
    if (appProcesses == null) {
      return false;
    }

    for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
      // The name of the process that this object is associated with.
      if (appProcess.processName.equals(packageName)
          && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
        return true;
      }
    }

    return false;
  }

  private final String TAG = "MPermissions";
  private int REQUEST_CODE_PERMISSION = 0x00099;
  private Dialog settingDialog;
  protected final int REQUEST_LOCAION_PERMISSIONS = 110;

  /**
   * 请求权限
   *
   * @param permissions 请求的权限
   * @param requestCode 请求权限的请求码
   */
  public void requestPermission(String[] permissions, int requestCode) {
    this.REQUEST_CODE_PERMISSION = requestCode;
    if (checkPermissions(permissions)) {
      permissionSuccess(REQUEST_CODE_PERMISSION);
    } else {
      List<String> needPermissions = getDeniedPermissions(permissions);
      ActivityCompat
          .requestPermissions(this, needPermissions.toArray(new String[needPermissions.size()]),
              REQUEST_CODE_PERMISSION);
    }
  }

  protected void requestPermission(List<String> list) {
    if (Util.listIsNull(list)) {
      return;
    }
    permissions = new String[list.size()];
    for (int i = 0; i < list.size(); i++) {
      permissions[i] = list.get(i);
    }
    requestPermission(permissions);
  }

  protected void requestPermission(String[] permissions) {
    RxPermissions rxPermission = new RxPermissions(this);
    rxPermission.requestEach(permissions)
        .subscribe(new Consumer<Permission>() {
          @Override
          public void accept(Permission permission) throws Exception {
            if (permission.granted) {
              // 用户已经同意该权限
              getPermissionSuccess();
            } else if (permission.shouldShowRequestPermissionRationale) {
              // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
//              showSettingDialog();
              getPermissionFail();
            } else {
              // 用户拒绝了该权限，并且选中『不再询问』
//              showSettingDialog();
              getPermissionFail();
            }
          }
        });
  }

  protected void getPermissionSuccess() {

  }

  protected void getPermissionFail() {

  }

  /**
   * 检测所有的权限是否都已授权
   */
  private boolean checkPermissions(String[] permissions) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
      return true;
    }

    for (String permission : permissions) {
      if (ContextCompat.checkSelfPermission(this, permission) !=
          PackageManager.PERMISSION_GRANTED) {
        return false;
      }
    }
    return true;
  }

  /**
   * 获取权限集中需要申请权限的列表
   */
  private List<String> getDeniedPermissions(String[] permissions) {
    List<String> needRequestPermissionList = new ArrayList<>();
    for (String permission : permissions) {
      if (ContextCompat.checkSelfPermission(this, permission) !=
          PackageManager.PERMISSION_GRANTED ||
          ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
        needRequestPermissionList.add(permission);
      }
    }
    return needRequestPermissionList;
  }


  /**
   * 系统请求权限回调
   */
  @Override
  public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
      @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == REQUEST_CODE_PERMISSION) {
      if (verifyPermissions(grantResults)) {
        permissionSuccess(REQUEST_CODE_PERMISSION);
      } else {
        permissionFail(REQUEST_CODE_PERMISSION);
        showSettingDialog();
      }
    }
  }

  /**
   * 确认所有的权限是否都已授权
   */
  private boolean verifyPermissions(int[] grantResults) {
    for (int grantResult : grantResults) {
      if (grantResult != PackageManager.PERMISSION_GRANTED) {
        return false;
      }
    }
    return true;
  }

  protected void showSettingDialog(IBaseActivityWorker worker) {
    if (null != settingDialog && settingDialog.isShowing()) {
      return;
    }
    settingDialog = new Dialog(context, R.style.mDialog);
    View view = getLayoutInflater().inflate(R.layout.dialog_modify, null);
    View layout = view.findViewById(R.id.dialog_modify_layout_ll);
    LinearLayout.LayoutParams ll = (LinearLayout.LayoutParams) layout.getLayoutParams();
    ll.width = ScreenUtil.getWidth() * 2 / 3;
    ll.height = LayoutParams.WRAP_CONTENT;
    layout.setLayoutParams(ll);
    TextView titileTv = view.findViewById(R.id.dialog_modify_title_tv);
    TextView contentTv = (TextView) view.findViewById(R.id.dialog_modify_content_tv);
    TextView sureTv = (TextView) view.findViewById(R.id.dialog_modify_sure_tv);
    TextView cancelTv = (TextView) view.findViewById(R.id.dialog_modify_cancel_tv);
    TextView listTv = (TextView) view.findViewById(R.id.dialog_modify_list_tv);
    AutoUtil.auto(view);
    settingDialog.setContentView(view);
    titileTv.setText("权限不可用");
    contentTv.setText("当前缺少必要权限，可能导致部分功能暂时无法使用。如若需要，请单击【去设置】按钮前往设置中心进行权限授权。");
    sureTv.setText("去设置");
    cancelTv.setText("稍后再说");
    sureTv.setOnClickListener(v -> {
      settingDialog.cancel();
      settingDialog.dismiss();
      if (null != worker) {
        worker.doSubmit();
      }
    });
    cancelTv.setOnClickListener(v -> {
      settingDialog.cancel();
      settingDialog.dismiss();
    });
    settingDialog.setCancelable(false);
    settingDialog.show();
  }

  protected void showSettingDialog() {
    settingDialog = new Dialog(context, R.style.mDialog);
    View view = getLayoutInflater().inflate(R.layout.dialog_modify, null);
    View layout = view.findViewById(R.id.dialog_modify_layout_ll);
    LinearLayout.LayoutParams ll = (LinearLayout.LayoutParams) layout.getLayoutParams();
    ll.width = !Util.isLarge() ?
        (int) (getWindowManager().getDefaultDisplay().getWidth()
            - getResources().getDimension(R.dimen.w116))
        : getWindowManager().getDefaultDisplay().getWidth() * 2 / 3;
    ll.height = ll.WRAP_CONTENT;
    layout.setLayoutParams(ll);
    TextView titileTv = (TextView) view.findViewById(R.id.dialog_modify_title_tv);
    TextView contentTv = (TextView) view.findViewById(R.id.dialog_modify_content_tv);
    TextView sureTv = (TextView) view.findViewById(R.id.dialog_modify_sure_tv);
    TextView cancelTv = (TextView) view.findViewById(R.id.dialog_modify_cancel_tv);
    TextView listTv = (TextView) view.findViewById(R.id.dialog_modify_list_tv);
    AutoUtil.auto(view);
    settingDialog.setContentView(view);
    titileTv.setText("权限不可用");
    List<String> list = PermissionUtils.getLocationPermissionNames();
    StringBuilder sb = new StringBuilder();
    if (!Util.listIsNull(list)) {
      for (int i = 0; i < list.size(); i++) {
        sb.append((i == list.size() - 1) ? list.get(i) : list.get(i) + "、");
      }
    }
    contentTv.setText("当前缺少必要权限，可能导致部分功能暂时无法使用。如若需要，请单击【去设置】按钮前往设置中心进行权限授权。");
    listTv.setText(TextUtil.Text(sb.toString()));
    sureTv.setText("去设置");
    cancelTv.setText("稍后再说");
    sureTv.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        settingDialog.cancel();
        settingDialog.dismiss();
        goToAppSetting();
      }
    });
    cancelTv.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        settingDialog.cancel();
        settingDialog.dismiss();
      }
    });
    settingDialog.setCancelable(false);
    settingDialog.show();
  }

  // 跳转到当前应用的设置界面
  private void goToAppSetting() {
    Intent intent = new Intent();
    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
    Uri uri = Uri.fromParts("package", getPackageName(), null);
    intent.setData(uri);
    startActivityForResult(intent, REQUEST_CODE_PERMISSION);
    overridePendingTransition(R.anim.in_from_right, R.anim.out_from_left);
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

  }

  /**
   * 启动当前应用设置页面
   */
  private void startAppSettings() {
    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
    intent.setData(Uri.parse("package:" + getPackageName()));
    startActivity(intent);
  }

  protected String[] permissions;

  protected Dialog permissionDialog;

  // 提示用户该请求权限的弹出框
  protected void showPermissionDialog(final List<String> listPer, List<String> perNames,
      final int code) {
    if (Util.listIsNull(listPer)) {
      return;
    }
    if (null != permissionDialog && permissionDialog.isShowing()) {
      return;
    }
    permissions = new String[listPer.size()];
    for (int i = 0; i < listPer.size(); i++) {
      permissions[i] = listPer.get(i);
    }
    permissionDialog = new Dialog(context, R.style.mDialog);
    permissionDialog.setContentView(R.layout.dialog_modify);
    View layout = permissionDialog.findViewById(R.id.dialog_modify_layout_ll);
    LinearLayout.LayoutParams ll = (LinearLayout.LayoutParams) layout.getLayoutParams();
    ll.width = getWindowManager().getDefaultDisplay().getWidth() - DensityUtil.dip2px(context, 58);
    ll.height = LayoutParams.WRAP_CONTENT;
    layout.setLayoutParams(ll);
    TextView titileTv = (TextView) permissionDialog.findViewById(R.id.dialog_modify_title_tv);
    TextView contentTv = (TextView) permissionDialog.findViewById(R.id.dialog_modify_content_tv);
    TextView sureTv = (TextView) permissionDialog.findViewById(R.id.dialog_modify_sure_tv);
    TextView cancelTv = (TextView) permissionDialog.findViewById(R.id.dialog_modify_cancel_tv);
    TextView listTv = (TextView) permissionDialog.findViewById(R.id.dialog_modify_list_tv);
    StringBuilder sb = new StringBuilder();
    if (!Util.listIsNull(perNames)) {
      for (int i = 0; i < perNames.size(); i++) {
        sb.append((i == perNames.size() - 1) ? perNames.get(i) : perNames.get(i) + "、");
      }
    }
    titileTv.setText("权限不可用");
    contentTv.setText("当前缺少必要功能权限，部分功能无法正常使用！请开启以下权限:");
    listTv.setText(TextUtil.Text(sb.toString()));
    sureTv.setText("立即开启");
    cancelTv.setText("稍后再说");
    sureTv.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        permissionDialog.cancel();
        permissionDialog.dismiss();
        requestPermission(permissions, code);
      }
    });
    cancelTv.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        permissionDialog.cancel();
        permissionDialog.dismiss();
      }
    });
    permissionDialog.setCancelable(false);
    permissionDialog.show();
  }

  protected void requestLocationPermission() {
    showPermissionDialog(PermissionUtils.getLocationNeedPermission(),
        PermissionUtils.getLocationPermissionNames(), REQUEST_LOCAION_PERMISSIONS);
  }

  /**
   * 获取权限成功
   */
  public void permissionSuccess(int requestCode) {
    Log.d(TAG, "获取权限成功=" + requestCode);

  }

  /**
   * 权限获取失败
   */
  public void permissionFail(int requestCode) {
    Log.d(TAG, "获取权限失败=" + requestCode);
  }

  public interface IBaseActivityWorker {

    void doSubmit();
  }
}
